<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="归属考试" prop="examId">
        <el-select v-model="queryParams.examId" placeholder="请选择考试" clearable style="width: 240px">
          <el-option v-for="item in examOptions" :key="item.id" :label="item.examName" :value="item.id" />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="题干" prop="content">-->
        <!--<el-input v-model="queryParams.content" placeholder="请输入题干关键词" clearable style="width: 240px" @keyup.enter.native="handleQuery" />-->
      <!--</el-form-item>-->
      <!-- <el-form-item label="标准答案" prop="answer">
        <el-select v-model="queryParams.answer" placeholder="请选择答案" clearable style="width: 240px">
          <el-option label="A" value="A" />
          <el-option label="B" value="B" />
          <el-option label="C" value="C" />
          <el-option label="D" value="D" />
        </el-select>
      </el-form-item>
      <el-form-item label="分值" prop="score">
        <el-select v-model="queryParams.score" placeholder="请选择分值" clearable style="width: 240px">
          <el-option label="1分" :value="1" />
          <el-option label="2分" :value="2" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:question:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:question:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:question:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="归属考试" align="center" prop="examName" :show-overflow-tooltip="true" />
      <el-table-column label="题干" align="center" prop="content" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="选项A" align="center" prop="option_a" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="选项B" align="center" prop="option_b" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="选项C" align="center" prop="option_c" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="选项D" align="center" prop="option_d" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="标准答案" align="center" prop="answer" width="100">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.answer }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分值" align="center" prop="score" width="80">
        <template slot-scope="scope">
          <el-tag type="warning">{{ scope.row.score }}分</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:question:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属考试" prop="examId">
              <el-select v-model="form.examId" placeholder="请选择考试" style="width: 100%">
                <el-option v-for="item in examOptions" :key="item.id" :label="item.examName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分值" prop="score">
              <el-select v-model="form.score" placeholder="请选择分值" style="width: 100%">
                <el-option label="1分" :value="1" />
                <el-option label="2分" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="题干" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入题干" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选项A" prop="option_a">
              <el-input v-model="form.option_a" placeholder="请输入选项A" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项B" prop="option_b">
              <el-input v-model="form.option_b" placeholder="请输入选项B" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选项C" prop="option_c">
              <el-input v-model="form.option_c" placeholder="请输入选项C" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项D" prop="option_d">
              <el-input v-model="form.option_d" placeholder="请输入选项D" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标准答案" prop="answer">
              <el-select v-model="form.answer" placeholder="请选择标准答案" style="width: 100%">
                <el-option label="A" value="A" />
                <el-option label="B" value="B" />
                <el-option label="C" value="C" />
                <el-option label="D" value="D" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="题目详情" :visible.sync="detailOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="归属考试">{{ detailForm.examName }}</el-descriptions-item>
        <el-descriptions-item label="分值">
          <el-tag type="warning">{{ detailForm.score }}分</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="题干" :span="2">{{ detailForm.content }}</el-descriptions-item>
        <el-descriptions-item label="选项A">{{ detailForm.option_a }}</el-descriptions-item>
        <el-descriptions-item label="选项B">{{ detailForm.option_b }}</el-descriptions-item>
        <el-descriptions-item label="选项C">{{ detailForm.option_c }}</el-descriptions-item>
        <el-descriptions-item label="选项D">{{ detailForm.option_d }}</el-descriptions-item>
        <el-descriptions-item label="标准答案">
          <el-tag type="success">{{ detailForm.answer }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailForm.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/system/question";
import { listExams } from "@/api/system/exams";

export default {
  name: "Question",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 考试选项
      examOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examId: null,
        content: null,
        answer: null,
        score: null
      },
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 表单校验
      rules: {
        examId: [
          { required: true, message: "归属考试不能为空", trigger: "change" }
        ],
        content: [
          { required: true, message: "题干不能为空", trigger: "blur" }
        ],
        option_a: [
          { required: true, message: "选项A不能为空", trigger: "blur" }
        ],
        option_b: [
          { required: true, message: "选项B不能为空", trigger: "blur" }
        ],
        option_c: [
          { required: true, message: "选项C不能为空", trigger: "blur" }
        ],
        option_d: [
          { required: true, message: "选项D不能为空", trigger: "blur" }
        ],
        answer: [
          { required: true, message: "标准答案不能为空", trigger: "change" }
        ],
        score: [
          { required: true, message: "分值不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    // 先获取考试选项，再获取题目列表
    this.getExamOptions().then(() => {
      this.getList();
    }).catch(() => {
      // 即使考试选项获取失败，也要获取题目列表
      this.getList();
    });
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        if (response.code === 200) {
          this.questionList = response.rows;
          this.total = response.total;
          // 确保考试名称正确显示
          this.questionList.forEach(question => {
            if (!question.examName && question.examId) {
              question.examName = this.getExamName(question.examId);
            }
          });
        } else {
          this.$modal.msgError("获取题目列表失败");
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取题目列表失败:", error);
        this.$modal.msgError("获取题目列表失败");
        this.loading = false;
      });
    },
    /** 查询考试选项 */
    getExamOptions() {
      return listExams({pageNum:1,pageSize:1000}).then(response => {
        if (response.code === 200) {
          this.examOptions = response.rows || [];
        } else {
          this.$modal.msgError("获取考试列表失败");
        }
      }).catch(error => {
        console.error("获取考试列表失败:", error);
        this.$modal.msgError("获取考试列表失败");
      });
    },
    /** 根据考试ID获取考试名称 */
    getExamName(examId) {
      if (!examId || !this.examOptions.length) {
        return '';
      }
      const exam = this.examOptions.find(item => item.id == examId);
      return exam ? exam.examName : '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        examId: null,
        content: null,
        option_a: null,
        option_b: null,
        option_c: null,
        option_d: null,
        answer: null,
        score: 1
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        if (response.code === 200) {
          this.form = response.data;
          // 确保考试选项已加载
          if (this.examOptions.length === 0) {
            this.getExamOptions().then(() => {
              // 考试选项加载完成后，再次设置表单数据
              this.form = response.data;
            });
          }
          this.form.examId = this.form.examId ? Number(this.form.examId) : ''
          this.form.score = this.form.score ? Number(this.form.score) : 1
          this.open = true;
          this.title = "修改题目";
        } else {
          this.$modal.msgError("获取题目信息失败");
        }
      }).catch(error => {
        console.error("获取题目信息失败:", error);
        this.$modal.msgError("获取题目信息失败");
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id;
      getQuestion(id).then(response => {
        if (response.code === 200) {
          this.detailForm = response.data;
          // 如果后端没有返回examName，则根据examId获取
          if (!this.detailForm.examName && this.detailForm.examId) {
            this.detailForm.examName = this.getExamName(this.detailForm.examId);
          }
          this.detailOpen = true;
        } else {
          this.$modal.msgError("获取题目详情失败");
        }
      }).catch(error => {
        console.error("获取题目详情失败:", error);
        this.$modal.msgError("获取题目详情失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.el-table .el-table__cell {
  padding: 8px 0;
}
</style>
